import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/pick/items/chart_info_row.dart';
import 'package:sports_new/view/pick/items/chart_match_info.dart';
import 'package:sports_new/view/pick/items/chart_notice.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import '../../../entity/ai/chart_bar_entity.dart';
import '../../../entity/ai/chart_match_entity.dart';
import '../../../resources/colours.dart';
import '../../../resources/styles.dart';
import '../../../server/api/ai_api.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/card.dart';
import '../ai/ai_type.dart';

class ChartBarPage extends StatefulWidget {
  const ChartBarPage({super.key, required this.type, required this.matchId});

  final AiType type;
  final int matchId;

  @override
  State<ChartBarPage> createState() => _ChartBarPageState();
}

class _ChartBarPageState extends State<ChartBarPage> {
  ChartBarEntity? entity;
  final Map<String,Color> borderColor = {"胜":Colours.blue2766D6,"平":Colours.grey66,"负":Colours.main};
  final Map<String,String> text = {"主胜":"胜","主负":"负","平局":"平"};

  @override
  void initState() {
    getData();
    super.initState();
  }

  Future getData() async{
    ChartBarEntity? data = await AiApi.getBar(widget.matchId,widget.type.tag);
    setState(() {
      entity = data;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.greyF2F3F7,
      appBar: Styles.appBar(
        titleSpacing: 0,
        titleTextStyle: const TextStyle(fontSize: 14,color: Colours.text),
        title: QkdText(widget.type.name??"",fontWeight: FontWeight.w500,fontSize: 18)
      ),
      body: LoadingWidget<int>(
        isLoading: entity == null,
        data: 1,
        child: () => SingleChildScrollView(
          child: Column(
            children: [
              Block(
                cardStyle: const CardStyle(
                  margin: EdgeInsets.fromLTRB(12, 12, 12, 0),
                ),
                child: Column(
                  children: [
                    Container(height: 12),
                    ChartMatchInfo(
                      info: ChartMatchEntity.fromJson(entity?.toJson()??{})
                    ),
                    Container(height: 20),
                    ChartInfoRow(
                      indexName: entity?.aiIndexName,
                      index: entity?.aiIndex,
                      level: (entity?.level??0)*(widget.type == AiType.assess?2:1),
                      advice: entity?.option?.join("、") ?? "",
                    )
                  ],
                )
              ),
              Block(
                cardStyle: const CardStyle(
                  margin: EdgeInsets.fromLTRB(12, 12, 12, 0),
                  padding: EdgeInsets.all(16)
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const QkdText("权威占比",
                        fontSize: 16,fontWeight: FontWeight.w500
                    ),
                    SizedBox(
                      height: 200,
                      child: BarChart(
                        BarChartData(
                          alignment: BarChartAlignment.spaceAround,
                          maxY: 100,
                          baselineY: -0.01,
                          barGroups: List.generate(
                            entity?.itemInfo?.length ?? 0,
                            (index) => bar(index)
                          ),
                          titlesData: FlTitlesData(
                            rightTitles: const AxisTitles(axisNameSize: 0),
                            topTitles: const AxisTitles(axisNameSize: 0),
                            leftTitles: AxisTitles(
                              sideTitles: SideTitles(
                                showTitles: true,
                                interval: 20,
                                reservedSize: 30,
                                getTitlesWidget: (value,meta) => SideTitleWidget(
                                  axisSide: meta.axisSide,
                                  child: QkdText(
                                    meta.formattedValue,
                                    color: Colours.grey99,
                                    fontSize: 12,
                                  ),
                                )
                              )
                            ),
                            bottomTitles: AxisTitles(
                              sideTitles: SideTitles(
                                showTitles: true,
                                getTitlesWidget: (value,meta) => SideTitleWidget(
                                  axisSide: meta.axisSide,
                                  child: QkdText(
                                    entity?.itemInfo?[value.toInt()].name ?? "",
                                    color: Colours.grey99,
                                    fontSize: 12,
                                  ),
                                )
                              )
                            )
                          ),
                          borderData: FlBorderData(
                            show: true,
                            border: const Border(
                              bottom: BorderSide(color: Colours.greyD7,width: 1)
                            )
                          ),
                          gridData: FlGridData(
                            drawVerticalLine: false,
                            horizontalInterval: 20,
                            getDrawingHorizontalLine: (value) => const FlLine(
                              color: Colours.greyD7,
                              dashArray: [3,3],
                              strokeWidth: 1
                            )
                          ),
                          barTouchData: BarTouchData(
                            touchTooltipData: BarTouchTooltipData(
                              getTooltipColor: (BarChartGroupData group){
                                return Colours.transparent;
                              },
                              tooltipPadding: EdgeInsets.zero,
                              tooltipMargin: 2,
                              getTooltipItem: (group, groupIndex, rod, rodIndex) {
                                var item = entity?.itemInfo?[groupIndex];
                                String text = "${((item?.rate??0)*100).toStringAsFixed(2)}% ${item?.info ?? ""}";
                                return BarTooltipItem(text, const TextStyle(fontSize: 12,color: Colours.text));
                              }
                            )
                          )
                        )
                      ),
                    ).paddingOnly(top: 24),
                    ChartNotice(tips: entity?.tips ?? [],margin: const EdgeInsets.only(top: 24)),
                    if(entity?.desc.hasValue??false)...[
                      Container(height: 24),
                      const QkdText("近期战绩",
                        fontSize: 16,fontWeight: FontWeight.w500
                      ),
                      Container(height: 12),
                      record()
                    ]

                  ],
                )
              )
            ],
          ),
        ),
      ),
    );
  }

  BarChartGroupData bar(int index){
    return BarChartGroupData(
      x: index,
      showingTooltipIndicators: [0],
      barRods: [
        BarChartRodData(
          width: 19,
          gradient: LinearGradient(
            colors: <Color>[
              const Color(0xFFF33F3F),
              const Color(0xFFF33F3F).withOpacity(0.1)
            ],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
          borderRadius: const BorderRadius.vertical(
            top: Radius.circular(4)
          ),
          toY: (
            (entity?.itemInfo?[index].rate ?? 0)*100
          ).toStringAsFixed(2).toDouble() ?? 0
        )
      ]
    );
  }

  Widget record(){
    return Block(
      cardStyle: const CardStyle(
          color: Color(0xFFF7FAFF),
          padding: EdgeInsets.fromLTRB(12, 8, 12, 8)
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 4,height: 4,
            margin: const EdgeInsets.only(top: 6),
            alignment: Alignment.centerLeft,
            decoration: const BoxDecoration(
              shape: BoxShape.circle,
              color: Colours.main
            )
          ),
          Container(width: 8),
          Flexible(
            child: QkdText(entity?.desc?.split("").join('\u200A') ?? "",
              color: Colours.grey66,
              maxLines: 2,letterSpacing: -0.8,
              needCenter: true,
            )
          )
        ]
      ),
    );
  }
}
